package com.itcam.phaseiii.thread_;

/**
 * Author:Cammy.Wu
 * Date:2024-05-10
 * Description:
 */

public class ThreadDemo03 {
    /*
            开启线程的第二种方式：实现Runnable接口

            1.编写一个类实现Runnable接口
            2.重写run
            3.将线程任务方法写在run方法中
            4.创建线程任务资源
            5.创建线程对象，将资源传入
            6.使用线程对象调用start，开启线程
     */
    public static void main(String[] args) {
        // 4.创建线程任务资源
        MyRunnable myRunnable = new MyRunnable();
        // 5.创建线程对象，将资源传入
        Thread t=new Thread(myRunnable);
        // 6.使用线程对象调用start，开启线程
        t.start();

        for (int i = 0; i <=2000; i++) {
            System.out.println("main线程被执行了");
        }
    }
}

// 1.编写一个类实现Runnable接口
class MyRunnable implements Runnable {

    /**
     * When an object implementing interface {@code Runnable} is used
     * to create a thread, starting the thread causes the object's
     * {@code run} method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method {@code run} is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    // 2.重写run
    @Override
    public void run() {
        // 3.将线程任务方法写在run方法中
        int sum = 0;
        for (int i = 0; i <= 200; i++) {
            sum+=i;
            System.out.println("线程任务执行了" + i);
        }
    }
}
